﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Budgeter.Models;

namespace Budgeter.ViewModels
{
    public static class ViewModelHelpers
    {

        /// <summary>
        /// Returns an array of items, with the index in the array matching the ID of
        /// each item.  This may result in some null entries in the array when the index doesn't
        /// have a corresponding ID.
        /// Intended to be used to create an array to allow for easy ID lookups in Javascript.
        /// </summary>
        /// <param name="intervals"></param>
        /// <returns></returns>
        public static T[] ToIdIndexedArray<T>(IEnumerable<T> items, Func<T, int> idGetter)
        {
            var maxId = items.Max(x => idGetter(x));
            var result = new List<T>();
            for (int i = 0; i <= maxId; i++)
                result.Add(items.SingleOrDefault(x => idGetter(x) == i));
            return result.ToArray();
        }

        public static IEnumerable<SelectListItem> GetIntervalSelectListItems(IEnumerable<Interval> items, int? selectedId = null)
        {
            return from i in items
                   select new SelectListItem
                   {
                       Value = i.IntervalId.ToString(),
                       Text = i.Name,
                       Selected = (i.IntervalId == selectedId),
                   };
        }

    }
}